package com.bamboo.framework.framework.security.service.impl;

import com.bamboo.framework.framework.security.entity.Menu;
import com.bamboo.framework.framework.security.entity.Role;
import com.bamboo.framework.framework.security.entity.RoleMenu;
import com.bamboo.framework.framework.security.mapper.RoleMenuMapper;
import com.bamboo.framework.framework.security.service.IMenuService;
import com.bamboo.framework.framework.security.service.IRoleMenuService;
import com.bamboo.framework.framework.security.service.IRoleService;
import com.bamboo.framework.common.format.ReturnMsg;
import com.bamboo.framework.common.enums.Status;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 菜单角色关联表 服务实现类
 * </p>
 *
 * @author 郭晴
 * @since 2018-12-19
 */
@Service
@Slf4j
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements
    IRoleMenuService {

  @Resource
  private IRoleService iRoleService;

  @Resource
  private IMenuService iMenuService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ReturnMsg saveMenu(Map<String, Object> map) {
    String roleId = String.valueOf(map.get("roleId"));
    List<Integer> menus = (List<Integer>) map.get("menus");
    System.out.println("RoleMenuServiceImpl.saveMenu"+menus.toString());
    if (StringUtil.isEmpty(roleId) || menus == null) {
      return new ReturnMsg(Status.PARAMETER_NULL, "roleId或menus不能为空");
    }

    Role role = iRoleService.getById(roleId);
    if (role == null) {
      return new ReturnMsg(Status.DATA_DOES_NOT_EXIST, "当前角色不存在");
    }

    boolean deleteByRoleId = this.remove(new QueryWrapper<RoleMenu>().eq("roleId", role.getId()));
    if (!deleteByRoleId) {
      return new ReturnMsg(Status.ERROR, "删除角色" + role.getRoleName() + "菜单关联表信息失败");
    }

      for (Integer menu : menus) {
        Menu byId = iMenuService.getById(menu);
        if (byId != null&&byId.getParentId()!=0) {
          RoleMenu roleMenu = new RoleMenu();
          roleMenu.setMenuId(menu);
          roleMenu.setRoleId(role.getId());
          this.save(roleMenu);
        }

      }

    return new ReturnMsg(Status.SUCCESS);
  }

  @Override
  public ReturnMsg getRoleMenuIdByRoleId(String roleId) {
    List<Integer> roleMenusId = new ArrayList<>();
    List<RoleMenu> rolemenus = this.list(new QueryWrapper<RoleMenu>().eq("roleId", roleId));
    for (RoleMenu rolemenu : rolemenus) {
      roleMenusId.add(rolemenu.getMenuId());
    }
    return new ReturnMsg(Status.SUCCESS, roleMenusId);
  }


}
